#!/usr/bin/env python3
# usage: python3 get_img_from_video.py mediafile [frame_num] [output_file] [threshold_type] [threshold] [max_value] [crop_info]
import cv2
import sys
from pathlib import Path
from operator import mod


try:
    mediafile = sys.argv[1]
except:
    mediafile = 'test.mp4'
media_name = mediafile.split('/')[-1].split('.')[0]

if not Path(media_name).is_dir():
    Path(media_name).mkdir(mode=0o777,parents=False)

try:
    shot_gap = int(sys.argv[2])
except:
    shot_gap = 25

media = cv2.VideoCapture(mediafile)
frames = int(media.get(cv2.CAP_PROP_FRAME_COUNT))
_,image = media.read()
imageHeight,imageWidth,_channels = image.shape

media = cv2.VideoCapture(mediafile)

frame_num = 0
while frame_num <= frames:
    _,img = media.read()
    frame_num += 1
    if mod(frame_num,shot_gap) == 0:

        crop_info = ''.join(['0:',str(imageHeight),',0:',str(imageWidth)])

        row_info,col_info = crop_info.split(',')
        start_row,end_row = row_info.split(':')
        start_col,end_col = col_info.split(':')

        output_file = ''.join([media_name,'/',media_name,'_',str(frame_num).zfill(6),'.jpg'])
        croped_img = img[int(start_row):int(end_row),int(start_col):int(end_col)]
        cv2.imwrite(output_file,croped_img)

